package com.sensitive.words.service;

import com.sensitive.words.mapper.SensitiveWordMapper;
import com.sensitive.words.model.SensitiveWordResult;
import com.sensitive.words.model.SensitiveWords;
import com.sensitive.words.utils.AhoCorasickAutomaton;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;


@Service
public class SensitiveWordServiceImpl implements SensitiveWordService {

    @Resource
    private AhoCorasickAutomaton automaton; // Aho-Corasick自动机实例

    @Resource
    private Set<String> sensitiveWords; // 存储敏感词的集


    @Override
    public void addSensitiveWord(String word) {
        // 如果敏感词集合中成功添加了新词，则更新自动机
        if (sensitiveWords.add(word)) {
            automaton.insert(word); // 插入新的敏感词
            automaton.buildFailurePointers(); // 重建自动机的失败指针
        }
    }

    @Override
    public List<SensitiveWordResult> findSensitiveWords(String text) {
        // 在给定文本中搜索敏感词
        return automaton.search(text);
    }

    @Override
    public void removeSensitiveWord(String word) {
        // 如果敏感词集合中成功删除了词，则重建自动机
        if (sensitiveWords.remove(word)) {
            automaton = new AhoCorasickAutomaton(); // 创建新的自动机实例
            for (String sw : sensitiveWords) {
                automaton.insert(sw); // 将剩余的敏感词插入新自动机
            }
            automaton.buildFailurePointers(); // 重建失败指针
        }
    }
}